<template>
  <div class="common-container">
    <el-breadcrumb separator="/"
                   class="common_breadcrumb">
      <el-breadcrumb-item @click="handleBack">数据集</el-breadcrumb-item>
      <el-breadcrumb-item>SQL</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true"
             :label-width="80"
             label-placement="left"
             :model="query"
             size="small">
      <el-form-item label="名称:"
                    prop="name">
        <el-input placeholder="请输入SQL名称"
                  v-model="query.name"
                  clearable
                  @keyup.enter.native="getMySqlList"
                  @change="getMySqlList"/>
      </el-form-item>
      <el-form-item label="数据源:"
                    prop="data_source_id">
        <el-select style="width: 140px"
                   placeholder="请选择数据源"
                   v-model="query.data_source_id"
                   :options="sourceList"
                   clearable
                   @change="getMySqlList"></el-select>
      </el-form-item>
      <el-form-item label="备注:"
                    prop="remark">
        <el-input placeholder="请输入备注"
                  v-model="query.remark"
                  @keyup.enter.native="getMySqlList"
                  clearable
                  @change="getMySqlList"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="getMySqlList">
          <el-icon style="vertical-align: middle;">
            <Search></Search>
          </el-icon>
          <span>查询</span>
        </el-button>
        <el-button type="success"
                   @click="handleModalAddAction">
          <el-icon style="vertical-align: middle;">
            <CirclePlus></CirclePlus>
          </el-icon>
          <span>新增</span>
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="sqlList"
              border
              style="width: 100%"
              v-loading="sqlLoading">
      <el-table-column type="index"
                       width="50"
                       title="序号"/>
      <el-table-column property="name"
                       align="center"
                       label="名称"/>
      <el-table-column align="center"
                       property="data_source_name"
                       label="数据源名称"/>
      <el-table-column property="data_source_type"
                       align="center"
                       label="数据源类型">
        <template #default="scope">
          <el-tag effect="dark"
                  size="small"
                  :type="showType(scope.row.data_source_type)">{{
              scope.row.data_source_type
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       property="remark"
                       label="备注"/>
      <el-table-column align="center"
                       property="create_timestamp"
                       label="创建时间"/>
      <el-table-column align="center"
                       label="操作">
        <template #default="scope">
          <el-button size="mini"
                     type="success"
                     @click="handleModalEditAction(scope.row)">更新
          </el-button>
          <el-button size="mini"
                     type="danger"
                     plain
                     @click="handleModalDelAction(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="common-pagination"
                   v-model:currentPage="pagination.page"
                   :page-size="pagination.size"
                   layout="prev, pager, next, jumper"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange">
    </el-pagination>
    <el-drawer v-model="SqlOpModel"
               :title="modalTitle[modalStatus]"
               size="28%"
               direction="rtl">
      <el-form :model="sqlForm"
               :rules="rules"
               ref="sqlFormRef"
               label-placement="left"
               label-width="80px"
               size="small">

        <el-form-item label="名称:"
                      prop="name">
          <el-input placeholder="请输入名称"
                    v-model="sqlForm.name"
                    clearable/>
        </el-form-item>
        <el-form-item label="数据源:"
                      prop="source_name">
          <el-select placeholder="请选择数据源"
                     v-model="sqlForm.data_source_id"
                     clearable
                     filterable>
            <el-option v-for="item in sourceList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:"
                      prop="remark">
          <el-input placeholder="请输入备注"
                    type="textarea"
                    v-model="sqlForm.remark"
                    clearable/>
        </el-form-item>
        <my-monaco-editor language="sql"
                          :code="sqlForm.code"
                          :auto-format="true"
                          @changeHandler="updateCode"
                          @blur="updateCode"></my-monaco-editor>
      </el-form>
      <div class="request-content">
        <div class="request-content_title">查询结果</div>
        <my-monaco-editor language="json"
                          :code="requestData"
                          :auto-format="true"></my-monaco-editor>
      </div>
      <div class="footer-modal">
        <el-button @click="handleCloseModal"
                   v-loading="formLoading"
                   size="small"
                   class="footer-modal--btn">取消
        </el-button>
        <el-button type="primary"
                   size="small"
                   class="footer-modal--btn"
                   v-loading="formLoading"
                   @click="handleTestSql">测试
        </el-button>
        <el-button v-if="modalStatus ==='add'"
                   type="primary"
                   size="small"
                   v-loading="formLoading"
                   class="footer-modal--btn  base-primary-btn m_lr_10"
                   :disabled="!submitFlag"
                   @click="handleAddSql">确认
        </el-button>
        <el-button v-if="modalStatus ==='edit'"
                   type="primary"
                   size="small"
                   v-loading="formLoading"
                   class="footer-modal--btn  base-primary-btn m_lr_10"
                   :disabled="!submitFlag"
                   @click="handleEditSql">更新
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from "vue";
import { addDataSql, delDataSql, editDataSql, getDataSqlList, testDataSql, } from "../../../service/data_sql";
import { allDataSource } from "../../../service/source";
import { useRouter } from "vue-router";
import { sqlTypeList } from "../../../utils/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Search } from "@element-plus/icons";

export default defineComponent({
  name: "my-data-sql",
  components: {CirclePlus, Search },
  setup() {
    const router = useRouter();
    const sqlList = ref([]);
    const total = ref(0);
    const SqlOpModel = ref(false);
    const sqlLoading = ref(false);
    const formLoading = ref(false);
    const modalStatus = ref("add");
    const sourceList = ref([]);
    const requestData = ref("");
    const modalTitle = ref({
      add: "新增Sql",
      edit: "编辑Sql",
    });
    const query = ref({
      limit: 10,
      size: 1,
      name: "",
      type: "",
      url: "",
      remark: "",
      data_source_id: "",
    });
    const handleSizeChange = (pageSize) => {
      query.value.page = 1;
      query.value.size = pageSize;
      getMySqlList();
    };
    const handleCurrentChange = (page) => {
      query.value.page = page;
      getMySqlList();
    };
    const pagination = ref({
      page: 1,
      size: 10,
    });
    const sqlForm = ref({
      name: undefined,
      data_source_id: undefined,
      remark: undefined,
      code: undefined,
    });
    const sqlFormRef = ref(null);
    const submitFlag = ref(false);
    const handleFormChange = () => {
      submitFlag.value = false;
    };
    const resetForm = () => {
      sqlForm.value = {
        name: undefined,
        data_source_id: undefined,
        remark: undefined,
        code: undefined,
      };
      requestData.value = "";
    };
    const handleModalAddAction = () => {
      resetForm();
      modalStatus.value = "add";
      SqlOpModel.value = true;
    };
    const handleCloseModal = () => {
      SqlOpModel.value = false;
    };
    const getMySqlList = () => {
      sqlLoading.value = true;
      getDataSqlList(query.value).then((res) => {
        sqlList.value = res.data.result;
        sqlLoading.value = false;
        total.value = res.data.total;
      });
    };
    const handleTestSql = () => {
      formLoading.value = true;
      sqlFormRef.value.validate((errors) => {
        if (!errors) {
          testDataSql(sqlForm.value)
              .then((res) => {
                formLoading.value = false;
                ElMessage({
                  type: "success",
                  message: "连接Sql成功",
                });
                submitFlag.value = true;
                requestData.value = JSON.stringify(res);
              })
              .catch(() => {
                ElMessage.error("连接Sql失败");
                formLoading.value = false;
              });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleAddSql = () => {
      formLoading.value = true;
      sqlFormRef.value.validate((errors) => {
        if (!errors) {
          addDataSql(sqlForm.value)
              .then(() => {
                formLoading.value = false;
                ElMessage({
                  type: "success",
                  message: "新增Sql成功",
                });
                handleCloseModal();
                getMySqlList();
              })
              .catch(() => {
                ElMessage.error("新增Sql失败");
                formLoading.value = false;
              });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleModalEditAction = (rowData) => {
      resetForm();
      sqlForm.value = rowData;
      modalStatus.value = "edit";
      submitFlag.value = false;
      SqlOpModel.value = true;
    };
    const handleEditSql = () => {
      formLoading.value = true;
      sqlFormRef.value.validate((errors) => {
        if (!errors) {
          editDataSql(sqlForm.value)
              .then(() => {
                formLoading.value = false;
                ElMessage({
                  type: "success",
                  message: "编辑Sql成功",
                });
                handleCloseModal();
                getMySqlList();
              })
              .catch(() => {
                ElMessage.error("编辑Sql失败");
                formLoading.value = false;
              });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(`你确定删除 ${rowData.name} 么？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        handleDelSql(rowData);
      });
    };
    const handleDelSql = (rowData) => {
      delDataSql({ data_sql_id: rowData.data_sql_id })
          .then(() => {
            ElMessage({
              type: "success",
              message: "删除Sql成功",
            });
            getMySqlList();
          })
          .catch((err) => {
            ElMessage.error("删除Sql失败");
          });
    };
    const handleBack = () => {
      router.push({ path: "index" });
    };
    const handleAllSource = () => {
      allDataSource().then((res) => {
        sourceList.value = res.data.result;
      });
    };
    const updateCode = (e) => {
      sqlForm.value.code = e.value;
    };
    const showType = (type) => {
      let tagType;
      switch (type) {
        case "PostgreSQL":
          tagType = "";
          break;
        case "Oracle":
          tagType = "info";
          break;
        case "MySQL":
          tagType = "warning";
          break;
        default:
          break;
      }
      return tagType;
    };
    onMounted(() => {
      getMySqlList();
      handleAllSource();
    });
    return {
      rules: {
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入Sql名称",
        },
        type: {
          required: true,
          message: "请选择Sql类型",
          trigger: ["change"],
        },
        server: {
          required: true,
          message: "请输入服务器地址",
          trigger: ["input", "blur"],
        },
      },
      query,
      total,
      sqlList,
      SqlOpModel,
      sqlForm,
      submitFlag,
      sqlFormRef,
      modalStatus,
      modalTitle,
      sourceList,
      formLoading,
      sqlLoading,
      updateCode,
      requestData,
      sqlTypeList: sqlTypeList,
      pagination,
      handleSizeChange,
      handleCurrentChange,
      getMySqlList,
      handleCloseModal,
      handleModalAddAction,
      handleFormChange,
      resetForm,
      handleDelSql,
      handleModalDelAction,
      handleModalEditAction,
      handleTestSql,
      handleAddSql,
      handleEditSql,
      handleBack,
      handleAllSource,
      showType,
    };
  },
});
</script>

<style lang="less" scoped>
.request-content {
  .request-content_title {
    font-size: 14px;
    margin: 12px 0 12px;
    font-weight: bolder;
  }
}
</style>
